<template>
  <el-dialog title="详情" width="850">
    <el-row>
      <el-col :span="8">
        <span class="label">用户ID：</span><span class="value">{{ detailData.userId }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">用户名：</span><span class="value">{{ detailData.name }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">电话：</span><span class="value">{{ detailData.mobile }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">签到天数：</span><span class="value">{{ detailData.signTimes }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">积分：</span><span class="value">{{ detailData.point }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">可提余额：</span><span class="value">{{ Math.min(detailData.gold, detailData.bindGold) / 100
          }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">冻结余额：</span><span class="value">{{ (detailData.bindGold - detailData.gold) / 100 }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">充值次数：</span><span class="value">{{ detailData.rechargeTimes }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">提现总金额:</span><span class="value">{{ detailData.withdrawNum / 100 }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">充值总金额:</span><span class="value">{{ detailData.rechargeNum / 100 }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">提现次数：</span><span class="value">{{ detailData.withdrawTimes }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">是否标记：</span><span class="value">{{ detailData.status == 0 ? "未标记" : "已标记" }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">注册IP：</span><span class="value">{{ detailData.registerIp }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">最近登录IP：</span><span class="value">{{ detailData.loginIp }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">注册时间：</span><span class="value">{{ formatDate(detailData.registerTime * 1000, "-") }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">最近登录时间：</span><span class="value">{{ formatDate(detailData.loginTime * 1000, "-") }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">密码：</span><span class="value">{{ detailData.pass }}</span>
      </el-col>
      <el-col :span="8">
        <span class="label">注册设备号：</span><span class="value">{{ detailData.mac }}</span>
      </el-col>
      <div style="display: flex; gap: 10px;" :style="{ display: flowPage.isEchart ? 'block' : 'none' }">
        <el-switch v-model="flowPage.isFullscreen" class="ml-2" inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="全屏" inactive-text="窗口" />
        <el-switch v-model="flowPage.isEchart" class="ml-2" inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="动账图表"
          inactive-text="动账记录" />
      </div>
    </el-row>
    <avue-crud ref="flowRef" :style="{ display: flowPage.isEchart ? 'none' : 'block' }"
      :class="{ fullscreen: flowPage.isFullscreen }" :cell-style="cellStyle" :table-loading="flowLoading"
      :option="flowOption" @refresh-change="getFlow" :data="flowData" :page="flowPage" @size-change="flowSizeChange"
      @current-change="flowCurrentChange" @search-change="flowSearchChange" @search-reset="flowSearchReset">
      <template #menu-left="{}">
        <div style="display: flex; gap: 10px;">
          <el-switch v-model="flowPage.isFullscreen" class="ml-2" inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="全屏" inactive-text="窗口" />
          <el-switch v-model="flowPage.isEchart" class="ml-2" inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="动账图表"
            inactive-text="动账记录" />
        </div>
      </template>
    </avue-crud>
    <div style="width: 100%;height: 300px;background: #f5f5f5;"
      :style="{ display: flowPage.isEchart ? 'block' : 'none' }">
      <div id="main" ref="chartContainer" style="width: 100%;height: 100%;"></div>
    </div>
  </el-dialog>
</template>

<script setup>
import * as echarts from 'echarts';
import { reactive, ref, watch, onMounted, onUnmounted } from 'vue';
import {
  getUserFlow,
} from "@/apis/admin";
const props = defineProps({
  visible: Boolean,
  detailData: Object
});

const emit = defineEmits(['update:visible']);
const innerVisible = ref(props.visible);

watch(() => props.visible, (newVal) => {
  innerVisible.value = newVal;
});

watch(innerVisible, (newVal) => {
  emit('update:visible', newVal);
});
const chartContainer = ref(null);
let myChart = null;
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  let style = {
  };
  if (columnIndex > 17) {
    return;
  }
  // style.backgroundColor = "#ffffff";
  // 随机一个0 1 2
  if (row.control === 0) {
  } else if (row.control === 1) {
    style.color = "#008000";
    style.backgroundColor = "#00800012";
  } else if (row.control === 2) {
    style.backgroundColor = "#f4433647";
  }

  return style;
};
const initChart = (data) => {
  if (chartContainer.value) {
    myChart = echarts.init(chartContainer.value, 'dark');

    // Prepare data for the series
    const dataList = data.map(item => (item.beforeGold / 100).toFixed(2));
    // dataList 反向排序
    const timesList = data.map(item => formatDate(item.createdAt * 1000, "-"));
    timesList.reverse();
    dataList.reverse();
    let piecesList = [];
    for (let i = 0; i < data.length; i++) {
      const item = data[i + 1];
      let _color = 'white';
      if (item) {
        if (item.control == 2) {
          _color = 'red';
        } else if (item.control == 1) {
          _color = 'green';
        }
      }

      piecesList.push({
        gt: i - 0.5, // Start of the range
        lte: i + 0.5, // End of the range
        color: _color
      });
    }
    piecesList.reverse();
    console.log('dataList:::--', dataList.length, piecesList);

    myChart.setOption({
      title: {
        text: '动账图表',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: timesList // Ensure this matches the data points
      },
      yAxis: {
        type: 'value',
        min: (value) => (value.min - value.max * 0.15).toFixed(2),
        max: (value) => (value.max * 1.15).toFixed(2)
      },
      visualMap: {
        show: false,
        dimension: 0,
        pieces: piecesList // Use piecesList directly
      },
      dataZoom: [
        {
          type: 'slider',
          show: true,
          xAxisIndex: [0],
          start: 0,
          end: 100
        },
        {
          type: 'inside',
          xAxisIndex: [0],
          start: 0,
          end: 100
        }
      ],
      series: [
        {
          name: 'Gold',
          type: 'line',
          smooth: true,
          data: dataList
        }
      ]
    });

    setTimeout(() => {
      window.dispatchEvent(new Event('resize'));
    }, 100);
  }
}

const flowPage = reactive({
  total: 0,
  pageSizes: [10, 40, 50, 100, 500, 1000],
  currentPage: 1,
  pageSize: 10,
  searchInfo: {},
  isFullscreen: false,
  isEchart: false
});

const flowLoading = ref(false);
const flowData = ref([]);

const flowOption = {
  index: true,
  border: true,
  stripe: true,
  height: "350",
  menuAlign: "center",
  loadingText: "加载中...",
  loadingSpinner: "svg",
  loadingSvgViewBox: "-10, -10, 50, 50",
  loadingBackground: "rgba(122, 122, 122, 0.6)",
  menu: false,
  addBtn: false,
  delBtn: false,
  editBtn: false,

  column: [
    { label: "服务", prop: "service" },
    { label: "服务编码", prop: "gameCode", minWidth: 130, search: true },
    {
      label: "动账前", prop: "beforeGold",
      formatter: (row) => row.beforeGold / 100,
    },
    {
      label: "动账后", prop: "afterGold",
      formatter: (row) => row.afterGold / 100,
    },
    {
      label: "金额变化", prop: "changeGold",
      formatter: (row) => row.changeGold / 100,
    },
    {
      label: "动账时间", prop: "createdAt", minWidth: 130,
      formatter: (row) => formatDate(row.createdAt * 1000, "-"),
    },
    {
      label: "原因", prop: "reason", minWidth: 130, search: true, searchType: "select",
      dicData: [
        { label: 'Active spin', value: 'Active spin' },
        { label: '输赢', value: '输赢' },
        { label: '下注', value: '下注' },
        { label: '前台充值', value: '前台充值' },
        { label: '后台充值', value: '后台充值' },
        { label: '提现', value: '提现' },
        { label: '活动奖励_spin', value: '活动奖励_spin' },
        { label: '邀请好友活动', value: '邀请好友活动' },
        { label: '活动奖励', value: '活动奖励' },
        { label: '兑换码', value: 'exchange' },
        { label: '首充活动奖励', value: '首充活动奖励' },
      ]
    },
  ],
};
onMounted(() => {
  window.addEventListener('resize', resizeChart);
});
onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (myChart) {
    myChart.dispose();
  }
});
const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
};
watch(() => props.visible, (newVal) => {
  if (newVal) {
    getFlow();
  }
});

const flowSizeChange = (val) => {
  flowPage.pageSize = val;
  getFlow();
};

const flowCurrentChange = (val) => {
  flowPage.currentPage = val;
  getFlow();
};

const flowSearchChange = (form, done) => {
  flowPage.searchInfo = form;
  getFlow();
  done();
};

const flowSearchReset = () => {
  flowPage.searchInfo = {};
  flowPage.currentPage = 1;
  getFlow();
};

const getFlow = () => {
  flowLoading.value = true;
  getUserFlow
    .post("", {
      userId: props.detailData.userId,
      page: flowPage.currentPage,
      pageSize: flowPage.pageSize,
      searchInfo: flowPage.searchInfo,
    })
    .then((res) => {
      console.log('res:::--', res)
      if (res.data.list) {
        initChart(res.data.list);
        flowData.value = res.data.list;
        flowPage.total = res.data.total;
      }
      flowLoading.value = false;
    });
};

const formatDate = (date, cut) => {
  var date = new Date(date);
  var YY = date.getFullYear() + cut;
  var MM =
    (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + cut;
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
};

watch(() => flowPage.isEchart, (newVal) => {
  console.log('newVal:::--', newVal)
  if (newVal) {
    if (myChart) {
      setTimeout(() => {
        myChart.resize();
      }, 100);
    }
  } else {

  }
});
</script>

<style scoped>
.subtitle {
  width: 100%;
  border-radius: 4px;
  background: #f5f5f5;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 15px;
  font-weight: 600;
  box-sizing: border-box;
  padding: 8px 10px;
  margin: 10px 0;
}

.label {
  color: #666;
  font-size: 12px;
  padding-right: 8px;
}

.value {
  color: #333;
  font-size: 13px;
}

.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: white;
  z-index: 9999;
  overflow: auto;
}
</style>
